package com.yyq.compare;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author yyq
 * @create 2021-08-03 20:59
 *
 * 二、Comparable接口的使用
 */
public class test {
    @Test
    public void test(){
        //String 实现了Comparable接口 重写了caompareTo()方法,给出了比较两个大小的规则
        //重写compareTo()规则
        //如果当前对象this 大于 形参对象obj 则返回正整数，小于返回负整数 等于返回 0
        String arr[]=new String[]{"AA","BB","CC","MM","SS","QQ"};
        Arrays.sort(arr);
        for(String i : arr)
        System.out.println(i);
    }


    public static void main(String[] args) {
        String arr[]=new String[]{"AA","BB","CC","MM","SS","QQ"};
        //按照字符串从大到小排序
        Arrays.sort(arr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(o1 instanceof String && o2 instanceof String){
                    String s1=(String)o1;
                    String s2=(String)o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("参数类型不符合");
            }
        });
        for (String s : arr) {
            System.out.println(s);
        }

    }
}
